package com.cw.handler;

import com.cw.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;


//设置异常捕获器
//全局异常处理
@RestControllerAdvice
@Slf4j
public class ExceptionGlobalHandler {

@ExceptionHandler(SQLIntegrityConstraintViolationException.class)
public R exception(SQLIntegrityConstraintViolationException e) {
        //获取报错信息
    String message = e.getMessage();
    log.info(message);
        if (message.contains("Duplicate entry")){
            String[] strings = message.split(" ");
            String msg =  "用户名"+strings[2]+"已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }

@ExceptionHandler(CustomException.class)
    public R customException(CustomException e) {
    log.info(e.getMessage());
    return R.error(e.getMessage());

    }
}
